<template>
  <div class="home-page">
    <nav-unit />
    <display-unit />
    <div class="center-content">
      <selfIntroduction />
      <div class="passages">
        <blog-preview v-for="blog in currentBlogs" :key="blog.id" :blog="blog" />
        <el-pagination background layout="prev, pager, next" :total="total" @current-change="changePage" />
      </div>
      <music-player />
    </div>
    <footer-unit />
  </div>
</template>

<script>
import NavUnit from '@/components/Navigation/NavUnit.vue'
import DisplayUnit from '@/components/DisplayCard/DisplayUnit.vue'
import SelfIntroduction from '@/components/Author/SelfIntroduction.vue'
import BlogPreview from '@/components/Blog/BlogPreview.vue'
import MusicPlayer from '@/components/Music/MusicPlayer.vue'
import FooterUnit from '@/components/Footer/FooterUnit.vue'
import axios from 'axios'
import { onBeforeMount, reactive, ref } from '@vue/runtime-core'

export default {
  name: 'HomePage',
  components: { 
    NavUnit,
    DisplayUnit,
    SelfIntroduction,
    BlogPreview,
    MusicPlayer,
    FooterUnit,
  },
  setup() {
    let blogs = []//所有blog不展示，不做响应式
    let currentBlogs = reactive([])//当前blog
    let total = ref(0)//文章总数

    const changePage = (page) => {
      currentBlogs.length = 0//奇怪的清空数组方式，直接赋值reative丢失响应式
      for(let i = 0; i < 3; i++) {
        let j = i+(page-1)*3
        if(j < blogs.length) {
          currentBlogs.push(blogs[j])
        }
      }
    }

    onBeforeMount(() => {
      axios.get('http://localhost/api/getBlog').then(res => {
        blogs = res.data
        blogs = blogs.reverse()
        total.value = Math.ceil(blogs.length/3)*10//total属性需要乘10才是页码数，鬼才设计
        //console.log(blogs)
        for(let i = 0; i < 3; i++) {
          if(i < blogs.length) {
            currentBlogs.push(blogs[i])
          }
        }
      }).catch(err => {
        console.log('未知错误！')
        console.log(err)
      })
    })

    return {
      blogs,
      currentBlogs,
      total,
      changePage
    }
  }
}
</script>

<style scoped>
  .center-content {
    display: flex;
    justify-content: space-between;
  }
  .passages {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0 50px;
  }
</style>